#!/usr/bin/python
 # -*- coding: utf8 -*-
import sys,socket,re,os

#quick and dirty webserver

def startServer(a):
	docroot="test"
	if(len(a)!=0):
		docroot=a[0]
	
	print("docroot is : "+docroot)

	HOST = ''                 # Symbolic name meaning all available interfaces
	PORT = 5000              # Arbitrary non-privileged port
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.bind((HOST, PORT))
	s.listen(1)
	
	while 1:
		conn,addr = s.accept()
		print('Connected by', addr)
		data = conn.recv(1024)
	
		what=re.split("\n",data)[0]
		para= re.split(" ",what)
		if(para[0]=="GET"):
			filename=para[1]
			print(filename)
			if(not re.match(r".*\..*",filename)):
				filename="/index.html"
			filename=docroot+filename
			print(filename)	
			content=""
			if os.path.isfile(filename):
				f= open(filename)
				for line in f:
					content=content+line
				f.close()
			else:
				content="page not found"	

			#header senden
			conn.send(content)	
		conn.close()
	


if __name__ == "__main__":
	startServer(sys.argv[1:])
	
